/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package z.h.w.jar.kit.clazz;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *
 * @param <Type>
 *
 * @author EnzoZhong
 */
public class Weight<Type> {

      private DecimalFormat decimalFormat = new DecimalFormat ( "0.00" );
      private Map<Type , Long> weight;

      /**
       *
       */
      public Weight () {
            weight = new HashMap<> ( 100 );
      }

      public void add ( List<Type> typeList ) {
            for ( Type type : typeList ) {
                  add ( type );
            }
      }

      /**
       *
       * @param val
       *
       * @return
       */
      public Long add ( Type val ) {
            if ( weight.containsKey ( val ) ) {
                  Long valWeight = weight.get ( val );
                  valWeight += 1l;
                  weight.put ( val , valWeight );
                  return valWeight;
            } else {
                  weight.put ( val , 1l );
                  return 1l;
            }
      }

      public Long get ( Type val ) {
            return weight.get ( val );
      }

      public Map<Type , Long> getWeight () {
            return weight;
      }

      public Long total () {
            Set<Type> keySet = weight.keySet ();
            Long total = 0l;
            for ( Type type : keySet ) {
                  total += weight.get ( type );
            }
            return total;
      }

      public Double average () {
            return total ().doubleValue () / weight.size ();
      }

      public Double percent ( Type val ) {
            return Double.parseDouble ( decimalFormat.format ( weight.get ( val ) * 100.0 / total () ) );
      }

      @Override
      public String toString () {
            StringBuffer stringBuffer = new StringBuffer ();
            stringBuffer.append ( "{\n" );
            Set<Type> keySey = weight.keySet ();
            for ( Type type : keySey ) {
                  stringBuffer.append ( type ).append ( " : " ).append ( weight.get ( type ) ).append ( "\n" );
            }
            stringBuffer.append ( "}" );
            return stringBuffer.toString ();
      }

}
